#include "BHeap.h"


void BHeap::insert(int x)
{

	cout << "insert " << x << endl;
	if (cursize++ == arraySize - 1)
	{
		m_array.resize(2 * arraySize);
	}

	int hole = cursize;
	
	cout << "insert " << x << " ";
	
	for (; hole > 1; hole = hole / 2)
	{
		if (x > m_array[hole / 2])
			break;
		

		else if (x == m_array[hole])
			return;

		m_array[hole] = m_array[hole / 2];

	}

	m_array[hole] = x;


	cout << "in pos " << hole << endl;
}


void BHeap::desc(int i)
{
	if (i > cursize){
		//cout << "!" << endl;
		return;
	}
		
	desc(2 * i);
	
	cout <<"pos "<< i << " " << m_array[i] << endl;
	
	desc(2 * i + 1);

}



void BHeap::deleteMin()
{
	if (cursize == 0)
		return;

	

	m_array[1] = m_array[cursize--];
	percolateDown(1);


}


void BHeap::percolateDown(int i)
{
	int temp = m_array[i];
	int child = 0;
	int hole = i;

	for (; hole * 2 < cursize; hole = child)
	{
		child = hole * 2;
		if (child < cursize && m_array[child + 1] < m_array[child])
			child++;
		if (temp > m_array[child]){
			cout << "put " << m_array[child] << " in the hole " << endl;
			m_array[hole] = m_array[child];
		}
			
		else
			break;

	}

	cout << "hole= " << hole << endl;
	m_array[hole] = temp;
}


void BHeap::percolateDown_standard(int i)
{


}

void BHeap::buildHeap(const vector<int> & theVec)
{
	for (int i = 0; i < theVec.size(); ++i)
	{
		m_array[i + 1] = theVec[i];

	}
	cursize = theVec.size();
	for (int i = cursize / 2; i > 0; --i)
	{
		percolateDown(i);
	}
}